package com.zheng.api.server.service.command;

import com.alibaba.fastjson.JSONObject;
import com.zheng.api.common.constant.ApiConstant;
import com.zheng.api.common.constant.ApiResult;
import com.zheng.api.common.constant.ApiResultConstant;
import com.zheng.api.server.service.ApiServerUmbrellaService;
import com.zheng.api.server.service.base.um.Base4UmbrellaService;
import com.zheng.api.server.service.mq.um.Mq4UmbrellaMachineNotify;
import com.zheng.api.server.service.mq.um.Mq4UmbrellaWechatappNotify;
import com.zheng.business.common.constant.BusinessConstant;
import com.zheng.business.dao.model.BusinessOrderUmbrellaConsumption;
import com.zheng.business.dao.model.BusinessOrderUmbrellaTimecard;
import com.zheng.common.constant.Constant;
import com.zheng.common.util.*;
import com.zheng.umbrella.dao.model.UmbrellaHardwareMachine;
import com.zheng.umbrella.dao.model.UmbrellaHardwareManageLog;
import com.zheng.umbrella.dao.model.UmbrellaHardwareManageLogExample;
import com.zheng.umbrella.dao.model.UmbrellaRuleDeposit;
import com.zheng.umbrella.rpc.api.UmbrellaHardwareManageLogService;
import com.zheng.upms.rpc.api.UpmsSystemParamService;
import com.zheng.wechat.mp.dao.model.WechatMpGzuser;
import com.zheng.wechat.mp.dao.model.WechatMpGzuserExample;
import com.zheng.wechat.mp.dao.model.WechatMpSystemAccount;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @Description: 小程序指令业务处理
 * @author lvb
 * @date 2017-09-05
 * @version V1.0
 * @Copyright: www.bjs-tech.com
 */
@Service
public class WechatBusiness4CommandServiceV1 extends Base4UmbrellaService implements WechatBusiness4CommandInterface{

    private static final Logger LOGGER = LoggerFactory.getLogger(WechatBusiness4CommandServiceV1.class);

    @Autowired
    ApiServerUmbrellaService apiServerUmbrellaService;
    @Autowired
    UmbrellaHardwareManageLogService umbrellaHardwareManageLogService;
    @Autowired
    Mq4UmbrellaMachineNotify mq4UmbrellaMachineNotify;
    @Autowired
    Mq4UmbrellaWechatappNotify mq4UmbrellaWechatappNotify;
    @Autowired
    UpmsSystemParamService upmsSystemParamService;

    /**
     * 缓存模块前缀
     */
    @Value("${Redis.CacheModule}")
    private String cacheModule;

    /**
     * 扫码下借伞订单(http/mqtt)【40101】
     * @param command
     * @param machineCode
     * @param code
     * @param message
     * @param recvData
     * @param isMqMessage
     */
    public ApiResult doCommand40101(String command,String machineCode, int code, String message, JSONObject recvData,boolean isMqMessage) {
        /**
         *
         {
             “command": 40101,
             “machineCode”:”2018092700001",
             “code”:1,//响应结果(1,成功；0，失败)
             "message":"",
             “data": {
                 “dataPackage”:{
                     “account”: 10000004,
                     “token”:”SDKJLJBB_JLKSDJFLKDSJFDSJFLJ-IJOIUEWRPOI”
                 }
             }
         }
         */
        JSONObject dataInfo = new JSONObject();
        ApiResult result = new ApiResult(ApiResultConstant.FAILED.code,ApiResultConstant.FAILED.message,ApiConstant.UMBRELLA_WECHATAPP_COMMAND_30101,machineCode,dataInfo);

        if (StringUtils.isEmpty(machineCode)) {
            result.setCode(ApiResultConstant.VERIFY_MACHINE_CODENOTNULL.code);
            result.setMessage(ApiResultConstant.VERIFY_MACHINE_CODENOTNULL.message);
            result.setData(dataInfo);
        }
         machineCode = machineCode==null?"":machineCode.substring(machineCode.lastIndexOf("/")+1);if("null".equals(machineCode)){machineCode = "";}
        int account = 0;
        try{
            account = recvData.getJSONObject("dataPackage").getInteger("account");
            if (StringUtils.isEmpty(account + "")) {
                result.setCode(ApiResultConstant.VERIFY_MACHINE_USERNOTNULL.code);
                result.setMessage(ApiResultConstant.VERIFY_MACHINE_USERNOTNULL.message);
                result.setData(dataInfo);
            }else {
                dataInfo.put("dataPackage", recvData.getJSONObject("dataPackage"));
                UmbrellaHardwareMachine umbrellaHardwareMachine = super.baseSelectUmbrellaHardwareMachineByStatus(machineCode, true);
                //状态是否在线
                if (umbrellaHardwareMachine == null ) {
                    //伞机尚未启用
                    result.setCode(ApiResultConstant.VERIFY_MACHINE_UNENABLED.code);
                    result.setMessage(ApiResultConstant.VERIFY_MACHINE_UNENABLED.message);
                    result.setData(dataInfo);
                } else if (umbrellaHardwareMachine.getAgentId()==null || StringUtils.isEmpty(String.valueOf(umbrellaHardwareMachine.getAgentId()))) {
                    //伞机归属未设置
                    result.setCode(ApiResultConstant.VERIFY_MACHINE_NOAGENT.code);
                    result.setMessage(ApiResultConstant.VERIFY_MACHINE_NOAGENT.message);
                    result.setData(dataInfo);
                } else if (umbrellaHardwareMachine.getRentRuleId()==null || StringUtils.isEmpty(String.valueOf(umbrellaHardwareMachine.getRentRuleId()))) {
                    //伞机租金规则未设置
                    result.setCode(ApiResultConstant.VERIFY_MACHINE_NORENTRULE.code);
                    result.setMessage(ApiResultConstant.VERIFY_MACHINE_NORENTRULE.message);
                    result.setData(dataInfo);
                } else {
                    //查询用户
                    WechatMpGzuser wechatMpGzuser = super.baseSelectWechatMpGzuser(account, true);
                    //更新用户归属代理
                    if((wechatMpGzuser!=null && wechatMpGzuser.getUserAgentId()==null) || (wechatMpGzuser!=null && !umbrellaHardwareMachine.getAgentId().equals(wechatMpGzuser.getUserAgentId()))){
                        WechatMpGzuser updateUser = new WechatMpGzuser();
                        updateUser.setUserAgentId(umbrellaHardwareMachine.getAgentId());
                        updateUser.setId(account);
                        int ret = super.updateWechatMpGzuserByPrimaryKeySelective(updateUser, account);
                        if(ret>0){
                            wechatMpGzuser.setUserAgentId(umbrellaHardwareMachine.getAgentId());
                        }
                    }

                    if (wechatMpGzuser == null) {
                        //用户不存在
                        result.setCode(ApiResultConstant.VERIFY_USER_UNREGISTERED.code);
                        result.setMessage(ApiResultConstant.VERIFY_USER_UNREGISTERED.message);
                        result.setData(dataInfo);
                    } else if (wechatMpGzuser.getUserstatus() == 2) {
                        //用户已被锁定
                        result.setCode(ApiResultConstant.VERIFY_USER_LOCKED.code);
                        result.setMessage(ApiResultConstant.VERIFY_USER_LOCKED.message);
                        result.setData(dataInfo);
                    } else {
                        //根据机器编号查询预付金规则
                        float machineDeposit = 0;
                        List<UmbrellaRuleDeposit> depositList = apiServerUmbrellaService.getRuleDeposit(account,machineCode);
                        if(depositList==null || depositList.size()==0) {
                            //伞机预付金规则未设置
                            result.setCode(ApiResultConstant.VERIFY_MACHINE_NODEPOSIT.code);
                            result.setMessage(ApiResultConstant.VERIFY_MACHINE_NODEPOSIT.message);
                            result.setData(dataInfo);
                        }else{
                            machineDeposit = depositList.get(0).getPrice()==null?0:depositList.get(0).getPrice().floatValue();
                            //用户存在，查询用户账户情况
                            WechatMpSystemAccount wechatMpSystemAccount = super.baseSelectWechatMpSystemAccont(account);

                            boolean isVip = false;
                            //用户购买的对应订单代理的时长卡
                            boolean isDifference = false;
                            try{
                                isDifference = "true".equals(upmsSystemParamService.querySystemParamValueByParam_key("BUSINESS_ORDER_TIMECARD_SETTLE_DIFF_AGENT"));
                            }catch(Exception e){}
                            BusinessOrderUmbrellaTimecard latestTimeCard =  super.baseSelectLastBusinessOrderUmbrellaTimecardNoCache(account,wechatMpGzuser.getUserAgentId(),isDifference);
                            Date nowDate = DateUtil.getDate();
                            //已购买时长卡还没到期
                            if(latestTimeCard!=null && latestTimeCard.getCardAfterEndtime()!=null && latestTimeCard.getCardAfterEndtime().after(nowDate)){
                                isVip = true;
                            }

                            if (wechatMpSystemAccount == null) {
                                //用户账号异常
                                result.setCode(ApiResultConstant.VERIFY_USER_ABNORMALITY.code);
                                result.setMessage(ApiResultConstant.VERIFY_USER_ABNORMALITY.message);
                                result.setData(dataInfo);
                            } else if (!isVip && machineDeposit!=0 && wechatMpSystemAccount.getDeposit().floatValue() == 0) {
                                //用户尚未缴纳预付金
                                result.setCode(ApiResultConstant.VERIFY_USER_DEPOSIT_UNPAID.code);
                                result.setMessage(ApiResultConstant.VERIFY_USER_DEPOSIT_UNPAID.message);
                                result.setData(dataInfo);
                            } else if (!isVip && machineDeposit!=0 && wechatMpSystemAccount.getDeposit().floatValue() < machineDeposit) {
                                //用户缴纳预付金不足
                                result.setCode(ApiResultConstant.VERIFY_USER_DEPOSIT_NOTENOUGH.code);
                                result.setMessage(ApiResultConstant.VERIFY_USER_DEPOSIT_NOTENOUGH.message);
                                result.setData(dataInfo);
                            } else if (!isVip && wechatMpSystemAccount.getAmount().floatValue() < 0) {
                                //用户余额不足
                                result.setCode(ApiResultConstant.VERIFY_USER_BALANCE_NOTENOUGH.code);
                                result.setMessage(ApiResultConstant.VERIFY_USER_BALANCE_NOTENOUGH.message);
                                result.setData(dataInfo);
                            } else if (wechatMpSystemAccount.getUmbrellanumber() > 0) {
                                //用户存在未归还雨伞
                                result.setCode(ApiResultConstant.VERIFY_USER_NOTRETURNED_UMBRELLA.code);
                                result.setMessage(ApiResultConstant.VERIFY_USER_NOTRETURNED_UMBRELLA.message);
                                result.setData(dataInfo);
                            } else {
                                //业务流水号
                                String bizSeqNo = BizSequenceUtils.getInstance().generateBizSeqNo(ModuleConstant.UMBRELLA_CONSUMPTION_BIZ_SEQUENCE_NO_PREFIX);
                                BusinessOrderUmbrellaConsumption businessOrderUmbrellaConsumption = new BusinessOrderUmbrellaConsumption();

                                Date time = DateUtil.getNowDate();
                                businessOrderUmbrellaConsumption.setOrderno(bizSeqNo);
                                businessOrderUmbrellaConsumption.setCreatetime(time);
                                businessOrderUmbrellaConsumption.setAgentid(umbrellaHardwareMachine.getAgentId());
                                businessOrderUmbrellaConsumption.setNickname(wechatMpGzuser.getNickname());
                                businessOrderUmbrellaConsumption.setUserid(account);
                                businessOrderUmbrellaConsumption.setMachineId(machineCode);
                                businessOrderUmbrellaConsumption.setRentAdress(umbrellaHardwareMachine.getAddress());
                                //初始化
                                businessOrderUmbrellaConsumption.setStatus(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_0);
                                //租金规则
                                businessOrderUmbrellaConsumption.setRentRuleId(Integer.valueOf(umbrellaHardwareMachine.getRentRuleId()));
                                //租金封顶金额
                                businessOrderUmbrellaConsumption.setLimitamount(new BigDecimal(0));
                                //未丢失
                                businessOrderUmbrellaConsumption.setLostStatus(0);
                                businessOrderUmbrellaConsumption.setRentamount(new BigDecimal(0));
                                businessOrderUmbrellaConsumption.setPayamount(new BigDecimal(0));
                                businessOrderUmbrellaConsumption.setDiscountedamount(new BigDecimal(0));
                                //保存
                                int ret = super.insertBusinessOrderUmbrellaConsumption(businessOrderUmbrellaConsumption);

                                //判断二次借伞
                                String isSecondFlag = "0";
                                String secondPath = cacheModule + ":" + ApiConstant.UMBRELLA_MACHINE_BORROW_SECONDFALG + ":" + account;
                                String secondFlag = RedisUtil.get(secondPath);
                                if (secondFlag != null) {
                                    isSecondFlag = "1";
                                }

                                //通知机器端开锁
                                /**
                                 {
                                 “command": 10101,
                                 "machineCode": "2018092700001",
                                 “code”:1,//响应结果(1,成功；0，失败)
                                 "message":"",
                                 “data": {
                                     “orderNo”:”20181101100020001”,//交互订单
                                     “isSecondFlag”:false,
                                     “dataPackage”:{
                                         “account”: 10000004,
                                         “token”:”SDKJLJBB_JLKSDJFLKDSJFDSJFLJ-IJOIUEWRPOI”
                                     }
                                 }
                                 }
                                 */
                                JSONObject machineDataInfo = new JSONObject();
                                machineDataInfo.put("orderNo", bizSeqNo);
                                machineDataInfo.put("isSecondFlag", isSecondFlag);
                                machineDataInfo.put("dataPackage", recvData.getJSONObject("dataPackage"));
                                ApiResult machineNotifyInfo = new ApiResult(ApiResultConstant.SUCCESS.code, ApiResultConstant.SUCCESS.message, ApiConstant.UMBRELLA_MACHINE_COMMAND_10101, machineCode, machineDataInfo);
                                mq4UmbrellaMachineNotify.send(JsonUtil.object2Json(machineNotifyInfo), machineCode);

                                //组装返回数据
                                dataInfo.put("orderNo", bizSeqNo);
                                result.setCode(ApiResultConstant.SUCCESS.code);
                                result.setMessage(ApiResultConstant.SUCCESS.message);
                                result.setData(dataInfo);
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            LOGGER.error("扫码预约借伞异常,异常信息:", e);
        }
        //使用mq消息将借伞处理失败通知客户端
        if(result.getCode() != ApiResultConstant.SUCCESS.code && account>0 && isMqMessage){
            mq4UmbrellaWechatappNotify.send(JsonUtil.object2Json(result), String.valueOf(account));
        }
        return result;
    }
    /**
     * 扫码预约还伞(http/mqtt)【40201】
     * @param command
     * @param machineCode
     * @param code
     * @param message
     * @param recvData
     * @param isMqMessage
     *
     */
    public ApiResult doCommand40201(String command,String machineCode, int code, String message, JSONObject recvData,boolean isMqMessage) {
        /**
         {
             “command": 40201,
             “machineCode”:”2018092700001",
             “code”:1,//响应结果(1,成功；0，失败)
             "message":"",
             “data": {
                 “dataPackage”:{
                     “account”: 10000004,
                     “token”:”SDKJLJBB_JLKSDJFLKDSJFDSJFLJ-IJOIUEWRPOI”
                  }
             }
         }
         */
        JSONObject dataInfo = new JSONObject();
        ApiResult result = new ApiResult(ApiResultConstant.FAILED.code, ApiResultConstant.FAILED.message, ApiConstant.UMBRELLA_WECHATAPP_COMMAND_30201,machineCode, dataInfo);
        if (StringUtils.isEmpty(machineCode)) {
            result.setCode(ApiResultConstant.VERIFY_MACHINE_CODENOTNULL.code);
            result.setMessage(ApiResultConstant.VERIFY_MACHINE_CODENOTNULL.message);
            result.setData(dataInfo);
        }
         machineCode = machineCode==null?"":machineCode.substring(machineCode.lastIndexOf("/")+1);if("null".equals(machineCode)){machineCode = "";}
        int account = 0;
        try {
            account = recvData.getJSONObject("dataPackage").getInteger("account");
            if (StringUtils.isEmpty(account + "")) {
                result.setCode(ApiResultConstant.VERIFY_MACHINE_USERNOTNULL.code);
                result.setMessage(ApiResultConstant.VERIFY_MACHINE_USERNOTNULL.message);
                result.setData(dataInfo);
            }else {
                dataInfo.put("dataPackage", recvData.getJSONObject("dataPackage"));
                //伞机在线
                UmbrellaHardwareMachine umbrellaHardwareMachine = super.baseSelectUmbrellaHardwareMachineByStatus(machineCode, true);
                //状态是否正常
                if (umbrellaHardwareMachine == null) {
                    //伞机尚未启用
                    result.setCode(ApiResultConstant.VERIFY_MACHINE_UNENABLED.code);
                    result.setMessage(ApiResultConstant.VERIFY_MACHINE_UNENABLED.message);
                    result.setData(dataInfo);
                } else {
                    //查询客户的借伞订单
                    BusinessOrderUmbrellaConsumption businessOrderUmbrellaConsumption = super.baseSelectBusinessOrderUmbrellaUnReturnByAccount(account,true);
                    //判断是否存在未归还雨伞
                    if (businessOrderUmbrellaConsumption != null) {
                        //组装机器端开锁指令信息
                        String orderNo = businessOrderUmbrellaConsumption.getOrderno();
                        String chipNumber = businessOrderUmbrellaConsumption.getChipNumber();
                        /**
                         {
                         “command": 10105,
                         "machineCode": "2018092700001",
                         “code”:1,//响应结果(1,成功；0，失败)
                         "message":"",
                         “data": {
                         “orderNo”:”20181101100020001”,//交互订单
                         “chipNumber”:”111111”,
                         “dataPackage”:{
                         “account”: 10000004,
                         “token”:”SDKJLJBB_JLKSDJFLKDSJFDSJFLJ-IJOIUEWRPOI”
                         }
                         }
                         }
                         */
                        JSONObject machineDataInfo = new JSONObject();
                        machineDataInfo.put("orderNo", orderNo);
                        machineDataInfo.put("chipNumber", chipNumber);
                        machineDataInfo.put("dataPackage", recvData.getJSONObject("dataPackage"));
                        ApiResult machineNotifyInfo = new ApiResult(ApiResultConstant.SUCCESS.code, ApiResultConstant.SUCCESS.message, ApiConstant.UMBRELLA_MACHINE_COMMAND_10105, machineCode, machineDataInfo);
                        mq4UmbrellaMachineNotify.send(JsonUtil.object2Json(machineNotifyInfo), machineCode);

                        //组装返回数据
                        dataInfo.put("orderNo", orderNo);
                        result.setCode(ApiResultConstant.SUCCESS.code);
                        result.setMessage(ApiResultConstant.SUCCESS.message);
                        result.setData(dataInfo);
                    } else {
                        result.setCode(ApiResultConstant.VERIFY_ORDER_NOTEXIST.code);
                        result.setMessage(ApiResultConstant.VERIFY_ORDER_NOTEXIST.message);
                        result.setData(dataInfo);
                    }
                }
            }
        }catch (Exception e){
            LOGGER.error("扫码预约还伞异常,异常信息:", e);
        }
        //使用mq消息将还伞处理失败通知客户端
        if(result.getCode() != ApiResultConstant.SUCCESS.code && account>0 && isMqMessage){
            mq4UmbrellaWechatappNotify.send(JsonUtil.object2Json(result), String.valueOf(account));
        }
        return result;
    }
    /**
     * 雨伞管理-进伞(http/mqtt)【40601】
     * @param command
     * @param machineCode
     * @param code
     * @param message
     * @param recvData
     */
    public ApiResult doCommand40601(String command,String machineCode, int code, String message, JSONObject recvData,boolean isMqMessage) {
        /**
         {
             “command": 40601,
             “machineCode”:”2018092700001",
             “code”:1,//响应结果(1,成功；0，失败)
             "message":"",
             “data": {
                 “dataPackage”:{
                     “account”: 10000004,
                     “token”:”SDKJLJBB_JLKSDJFLKDSJFDSJFLJ-IJOIUEWRPOI”
                 }
             }
         }
         */
        JSONObject dataInfo = new JSONObject();
        ApiResult result = new ApiResult(ApiResultConstant.FAILED.code, ApiResultConstant.FAILED.message, ApiConstant.UMBRELLA_WECHATAPP_COMMAND_30601,machineCode, dataInfo);
         machineCode = machineCode==null?"":machineCode.substring(machineCode.lastIndexOf("/")+1);if("null".equals(machineCode)){machineCode = "";}
        if (StringUtils.isEmpty(machineCode)) {
            result.setCode(ApiResultConstant.VERIFY_MACHINE_CODENOTNULL.code);
            result.setMessage(ApiResultConstant.VERIFY_MACHINE_CODENOTNULL.message);
            result.setData(dataInfo);
        }
         machineCode = machineCode==null?"":machineCode.substring(machineCode.lastIndexOf("/")+1);if("null".equals(machineCode)){machineCode = "";}
        int account = 0;
        try {
            account = recvData.getJSONObject("dataPackage").getInteger("account");
            dataInfo.put("dataPackage", recvData.getJSONObject("dataPackage"));
            if (StringUtils.isEmpty(account + "")) {
                result.setCode(ApiResultConstant.VERIFY_MACHINE_USERNOTNULL.code);
                result.setMessage(ApiResultConstant.VERIFY_MACHINE_USERNOTNULL.message);
                result.setData(dataInfo);
            }else{
                //查询用户
                WechatMpGzuser wechatMpGzuser = super.baseSelectWechatMpGzuser(account, true);
                //查询伞机是否在线
                UmbrellaHardwareMachine umbrellaHardwareMachine = super.baseSelectUmbrellaHardwareMachineByStatus(machineCode, true);
                //判断伞机状态
                if (umbrellaHardwareMachine == null) {
                    result.setCode(ApiResultConstant.VERIFY_MACHINE_UNENABLED.code);
                    result.setMessage(ApiResultConstant.VERIFY_MACHINE_UNENABLED.message);
                    result.setData(dataInfo);
                }else{
                    //超级代理或对应代理才能管理
                    if(wechatMpGzuser.getAgentId() == 1 || (wechatMpGzuser.getManage() == 1 && wechatMpGzuser.getAgentId() == umbrellaHardwareMachine.getAgentId())){

                        int seconds = Integer.parseInt(upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_MAINTAINTIMEOUT"));

                        UmbrellaHardwareManageLogExample logExample = new UmbrellaHardwareManageLogExample();
                        UmbrellaHardwareManageLogExample.Criteria logCriteria = logExample.createCriteria();
                        //未删除
                        logCriteria.andFlagEqualTo(1);
                        //状态初始化
                        logCriteria.andResultEqualTo(0);
                        logCriteria.andMachineCodeEqualTo(machineCode);
                        logCriteria.andCommandEqualTo(ApiConstant.UMBRELLA_MACHINE_COMMAND_10110);
                        logExample.setOrderByClause("start_time desc");    //确保获取到最新的数据
                        UmbrellaHardwareManageLog log = umbrellaHardwareManageLogService.selectFirstByExample(logExample);
                        // 如果log为空 或者log的时间已经超过指定结束时间
                        if (log == null || DateUtil.getNowDate().getTime() - log.getStartTime().getTime() > (seconds + 10) * 1000) {
                            Date beginTime = DateUtil.getNowDate();
                            //订单号
                            final String orderNo = BizSequenceUtils.getInstance().generateBizSeqNo(ModuleConstant.UMBRELLA_COMMON_BIZ_SEQUENCE_NO_PREFIX);
                            log = new UmbrellaHardwareManageLog();
                            log.setOrderno(orderNo);
                            log.setUserid(account);
                            log.setMachineCode(machineCode);
                            log.setCommand(ApiConstant.UMBRELLA_MACHINE_COMMAND_10110);
                            log.setStartTime(beginTime);
                            log.setResult(0);
                            log.setUmbrellacount(0);
                            log.setUmbrellalist("");
                            log.setFlag(Constant.CONST_FLAG_NORMAL);
                            log.setCtime(beginTime);
                            int ret = umbrellaHardwareManageLogService.insert(log);
                            if (ret > 0) {
                                //通知机器端开锁
                                /**
                                 {
                                 "command": 10110,
                                 “machineCode”:”2018092700001",
                                 “code”:1,//响应结果(1,成功；0，失败)
                                 "message":"",
                                 "dataInfo": {
                                 “orderNo":”20180929100020001",//交互订单
                                 “dataPackage”:{
                                 “account”: 10000004,
                                 “token”:”SDKJLJBB_JLKSDJFLKDSJFDSJFLJ-IJOIUEWRPOI”
                                 }
                                 }
                                 }
                                 */
                                JSONObject machineDataInfo = new JSONObject();
                                machineDataInfo.put("orderNo", orderNo);
                                machineDataInfo.put("dataPackage", recvData.getJSONObject("dataPackage"));
                                ApiResult machineNotifyInfo = new ApiResult(ApiResultConstant.SUCCESS.code, ApiResultConstant.SUCCESS.message, ApiConstant.UMBRELLA_MACHINE_COMMAND_10110, machineCode, machineDataInfo);
                                mq4UmbrellaMachineNotify.send(JsonUtil.object2Json(machineNotifyInfo), machineCode);

                                //组装返回数据
                                dataInfo.put("orderNo", orderNo);
                                result.setCode(ApiResultConstant.SUCCESS.code);
                                result.setMessage(ApiResultConstant.SUCCESS.message);
                                result.setData(dataInfo);
                            } else {
                                result.setCode(ApiResultConstant.FAILED.code);
                                result.setMessage(ApiResultConstant.FAILED.message);
                                result.setData(dataInfo);
                            }
                        } else {
                            result.setCode(ApiResultConstant.FAILED.code);
                            result.setMessage(ApiResultConstant.FAILED.message);
                            result.setData(dataInfo);
                        }
                    } else {
                        result.setCode(ApiResultConstant.FAILED.code);
                        result.setMessage(ApiResultConstant.FAILED.message);
                        result.setData(dataInfo);
                    }
                }
            }
        }catch (Exception e){
            LOGGER.error("扫码进伞异常,异常信息:", e);
        }
        //使用mq消息将扫码进伞处理失败通知客户端
        if(result.getCode() != ApiResultConstant.SUCCESS.code && account>0 && isMqMessage){
            mq4UmbrellaWechatappNotify.send(JsonUtil.object2Json(result), String.valueOf(account));
        }
        return result;
    }
    /**
     * 雨伞管理-结束进伞(http/mqtt)【40602】
     * @param command
     * @param machineCode
     * @param code
     * @param message
     * @param recvData
     */
    public ApiResult doCommand40602(String command,String machineCode, int code, String message, JSONObject recvData,boolean isMqMessage) {

        JSONObject dataInfo = new JSONObject();
        ApiResult result = new ApiResult(ApiResultConstant.FAILED.code, ApiResultConstant.FAILED.message, ApiConstant.UMBRELLA_WECHATAPP_COMMAND_30601,machineCode, dataInfo);
         machineCode = machineCode==null?"":machineCode.substring(machineCode.lastIndexOf("/")+1);if("null".equals(machineCode)){machineCode = "";}
        if (StringUtils.isEmpty(machineCode)) {
            result.setCode(ApiResultConstant.VERIFY_MACHINE_CODENOTNULL.code);
            result.setMessage(ApiResultConstant.VERIFY_MACHINE_CODENOTNULL.message);
            result.setData(dataInfo);
        }
        int account = 0;
        try {
            account = recvData.getJSONObject("dataPackage").getInteger("account");
            dataInfo.put("dataPackage", recvData.getJSONObject("dataPackage"));
            if (StringUtils.isEmpty(account + "")) {
                result.setCode(ApiResultConstant.VERIFY_MACHINE_USERNOTNULL.code);
                result.setMessage(ApiResultConstant.VERIFY_MACHINE_USERNOTNULL.message);
                result.setData(dataInfo);
            }else {
                //查询伞机是否在线
                UmbrellaHardwareMachine umbrellaHardwareMachine = super.baseSelectUmbrellaHardwareMachineByStatus(machineCode, true);
                //判断伞机状态
                if (umbrellaHardwareMachine == null) {
                    result.setCode(ApiResultConstant.VERIFY_MACHINE_UNENABLED.code);
                    result.setMessage(ApiResultConstant.VERIFY_MACHINE_UNENABLED.message);
                    result.setData(dataInfo);
                } else {
                    //订单号
                    UmbrellaHardwareManageLogExample logExample = new UmbrellaHardwareManageLogExample();
                    UmbrellaHardwareManageLogExample.Criteria logCriteria = logExample.createCriteria();
                    //未删除
                    logCriteria.andFlagEqualTo(1);
                    //状态初始化
                    logCriteria.andResultEqualTo(0);
                    logCriteria.andUseridEqualTo(account);
                    logCriteria.andMachineCodeEqualTo(machineCode);
                    logCriteria.andEndTimeIsNull();
                    logCriteria.andCommandEqualTo(ApiConstant.UMBRELLA_MACHINE_COMMAND_10110);
                    logExample.setOrderByClause("start_time desc");
                    UmbrellaHardwareManageLog log = umbrellaHardwareManageLogService.selectFirstByExample(logExample);
                    if (log != null) {

                        //通知机器端关锁
                        /**
                         {
                         "command": 10111,
                         “machineCode”:”2018092700001",
                         “code”:1,//响应结果(1,成功；0，失败)
                         "message":"",
                         "dataInfo": {
                             “orderNo":”20180929100020001",//交互订单
                             “dataPackage”:{
                                 “account”: 10000004,
                                 “token”:”SDKJLJBB_JLKSDJFLKDSJFDSJFLJ-IJOIUEWRPOI”
                               }
                             }
                         }
                         */
                        JSONObject machineDataInfo = new JSONObject();
                        machineDataInfo.put("orderNo", log.getOrderno());
                        machineDataInfo.put("dataPackage", recvData.getJSONObject("dataPackage"));
                        ApiResult machineNotifyInfo = new ApiResult(ApiResultConstant.SUCCESS.code, ApiResultConstant.SUCCESS.message, ApiConstant.UMBRELLA_MACHINE_COMMAND_10111, machineCode, machineDataInfo);
                        mq4UmbrellaMachineNotify.send(JsonUtil.object2Json(machineNotifyInfo), machineCode);

                        //组装返回数据
                        dataInfo.put("orderNo", log.getOrderno());
                        result.setCode(ApiResultConstant.SUCCESS.code);
                        result.setMessage(ApiResultConstant.SUCCESS.message);
                        result.setData(dataInfo);
                    } else {
                        result.setCode(ApiResultConstant.FAILED.code);
//                        result.setMessage(ApiResultConstant.FAILED.message);
                        result.setMessage("伞机进伞操作已结束。");
                        result.setData(dataInfo);
                    }

                }
            }
        }catch (Exception e){
            LOGGER.error("扫码结束进伞异常,异常信息:", e);
        }
        //使用mq消息将还伞处理失败通知客户端
        if(result.getCode() != ApiResultConstant.SUCCESS.code && account>0 && isMqMessage){
            mq4UmbrellaWechatappNotify.send(JsonUtil.object2Json(result), String.valueOf(account));
        }
        return result;
    }
    /**
     * 雨伞管理-出伞(http/mqtt)【40701】
     * @param command
     * @param machineCode
     * @param code
     * @param message
     * @param recvData
     */
    public ApiResult doCommand40701(String command,String machineCode, int code, String message, JSONObject recvData,boolean isMqMessage) {
        JSONObject dataInfo = new JSONObject();
        ApiResult result = new ApiResult(ApiResultConstant.FAILED.code, ApiResultConstant.FAILED.message, ApiConstant.UMBRELLA_WECHATAPP_COMMAND_30701,machineCode, dataInfo);
         machineCode = machineCode==null?"":machineCode.substring(machineCode.lastIndexOf("/")+1);if("null".equals(machineCode)){machineCode = "";}
        if (StringUtils.isEmpty(machineCode)) {
            result.setCode(ApiResultConstant.VERIFY_MACHINE_CODENOTNULL.code);
            result.setMessage(ApiResultConstant.VERIFY_MACHINE_CODENOTNULL.message);
            result.setData(dataInfo);
        }
        int account = 0;
        try {
            account = recvData.getJSONObject("dataPackage").getInteger("account");
            dataInfo.put("dataPackage", recvData.getJSONObject("dataPackage"));
            if (StringUtils.isEmpty(account + "")) {
                result.setCode(ApiResultConstant.VERIFY_MACHINE_USERNOTNULL.code);
                result.setMessage(ApiResultConstant.VERIFY_MACHINE_USERNOTNULL.message);
                result.setData(dataInfo);
            }else {
                //查询用户
                WechatMpGzuser wechatMpGzuser = super.baseSelectWechatMpGzuser(account, true);
                //查询伞机
                UmbrellaHardwareMachine umbrellaHardwareMachine = super.baseSelectUmbrellaHardwareMachineByStatus(machineCode,true);
                //判断伞机状态
                if(umbrellaHardwareMachine == null){
                    result.setCode(ApiResultConstant.VERIFY_MACHINE_UNENABLED.code);
                    result.setMessage(ApiResultConstant.VERIFY_MACHINE_UNENABLED.message);
                    result.setData(dataInfo);
                }else {
                    //超级代理或对应代理才能管理
                    if(wechatMpGzuser.getAgentId() == 1 || (wechatMpGzuser.getManage() == 1 && wechatMpGzuser.getAgentId() == umbrellaHardwareMachine.getAgentId())){
                        int seconds = Integer.parseInt(upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_MAINTAINTIMEOUT"));
                        UmbrellaHardwareManageLogExample logExample = new UmbrellaHardwareManageLogExample();
                        UmbrellaHardwareManageLogExample.Criteria logCriteria = logExample.createCriteria();
                        //未删除
                        logCriteria.andFlagEqualTo(1);
                        //状态初始化
                        logCriteria.andResultEqualTo(0);
                        logCriteria.andMachineCodeEqualTo(machineCode);
                        logCriteria.andCommandEqualTo(ApiConstant.UMBRELLA_MACHINE_COMMAND_10112);
                        logExample.setOrderByClause("start_time desc");    //确保获取到最新的数据
                        UmbrellaHardwareManageLog log = umbrellaHardwareManageLogService.selectFirstByExample(logExample);
                        // 如果log为空 或者log的时间已经超过指定结束时间
                        if (log == null || DateUtil.getNowDate().getTime() - log.getStartTime().getTime() > (seconds + 10) * 1000) {
                            Date beginTime = DateUtil.getNowDate();
                            //订单号
                            String orderNo = BizSequenceUtils.getInstance().generateBizSeqNo(ModuleConstant.UMBRELLA_COMMON_BIZ_SEQUENCE_NO_PREFIX);
                            log = new UmbrellaHardwareManageLog();
                            log.setOrderno(orderNo);
                            log.setUserid(account);
                            log.setMachineCode(machineCode);
                            log.setCommand(ApiConstant.UMBRELLA_MACHINE_COMMAND_10112);
                            log.setStartTime(beginTime);
                            log.setResult(0);
                            log.setUmbrellacount(0);
                            log.setUmbrellalist("");
                            log.setFlag(Constant.CONST_FLAG_NORMAL);
                            log.setCtime(beginTime);
                            int ret = umbrellaHardwareManageLogService.insert(log);
                            if (ret > 0) {
                                //通知机器端开锁
                                /**
                                 {
                                 "command": 10112,
                                 “machineCode”:”2018092700001",
                                 “code”:1,//响应结果(1,成功；0，失败)
                                 "message":"",
                                 "dataInfo": {
                                 “orderNo":”20180929100020001",//交互订单
                                 “dataPackage”:{
                                 “account”: 10000004,
                                 “token”:”SDKJLJBB_JLKSDJFLKDSJFDSJFLJ-IJOIUEWRPOI”
                                 }
                                 }
                                 }
                                 */
                                JSONObject machineDataInfo = new JSONObject();
                                machineDataInfo.put("orderNo", log.getOrderno());
                                machineDataInfo.put("dataPackage", recvData.getJSONObject("dataPackage"));
                                ApiResult machineNotifyInfo = new ApiResult(ApiResultConstant.SUCCESS.code, ApiResultConstant.SUCCESS.message, ApiConstant.UMBRELLA_MACHINE_COMMAND_10112, machineCode, machineDataInfo);
                                mq4UmbrellaMachineNotify.send(JsonUtil.object2Json(machineNotifyInfo), machineCode);

                                //组装返回数据
                                dataInfo.put("orderNo", log.getOrderno());
                                result.setCode(ApiResultConstant.SUCCESS.code);
                                result.setMessage(ApiResultConstant.SUCCESS.message);
                                result.setData(dataInfo);
                            } else {
                                result.setCode(ApiResultConstant.FAILED.code);
                                result.setMessage(ApiResultConstant.FAILED.message);
                                result.setData(dataInfo);
                            }
                        } else {
                            result.setCode(ApiResultConstant.FAILED.code);
                            result.setMessage(ApiResultConstant.FAILED.message);
                            result.setData(dataInfo);
                        }
                    }
                }
            }
        }catch (Exception e){
            LOGGER.error("扫码出伞处理异常,异常信息:", e);
        }
        //使用mq消息将扫码出伞处理失败通知客户端
        if(result.getCode() != ApiResultConstant.SUCCESS.code && account>0 && isMqMessage){
            mq4UmbrellaWechatappNotify.send(JsonUtil.object2Json(result), String.valueOf(account));
        }
        return result;
    }
    /**
     * 雨伞管理-结束出伞(http/mqtt)【40702】
     * @param command
     * @param machineCode
     * @param code
     * @param message
     * @param recvData
     */
    public ApiResult doCommand40702(String command,String machineCode, int code, String message, JSONObject recvData,boolean isMqMessage) {

        JSONObject dataInfo = new JSONObject();
        ApiResult result = new ApiResult(ApiResultConstant.FAILED.code, ApiResultConstant.FAILED.message, ApiConstant.UMBRELLA_WECHATAPP_COMMAND_30701,machineCode, dataInfo);
         machineCode = machineCode==null?"":machineCode.substring(machineCode.lastIndexOf("/")+1);if("null".equals(machineCode)){machineCode = "";}
        if (StringUtils.isEmpty(machineCode)) {
            result.setCode(ApiResultConstant.VERIFY_MACHINE_CODENOTNULL.code);
            result.setMessage(ApiResultConstant.VERIFY_MACHINE_CODENOTNULL.message);
            result.setData(dataInfo);
        }
        int account = 0;
        try {
            account = recvData.getJSONObject("dataPackage").getInteger("account");
            dataInfo.put("dataPackage", recvData.getJSONObject("dataPackage"));
            if (StringUtils.isEmpty(account + "")) {
                result.setCode(ApiResultConstant.VERIFY_MACHINE_USERNOTNULL.code);
                result.setMessage(ApiResultConstant.VERIFY_MACHINE_USERNOTNULL.message);
                result.setData(dataInfo);
            }else {
                //查询伞机
                UmbrellaHardwareMachine umbrellaHardwareMachine = super.baseSelectUmbrellaHardwareMachineByStatus(machineCode, true);
                //判断伞机状态
                if (umbrellaHardwareMachine == null) {
                    result.setCode(ApiResultConstant.VERIFY_MACHINE_UNENABLED.code);
                    result.setMessage(ApiResultConstant.VERIFY_MACHINE_UNENABLED.message);
                    result.setData(dataInfo);
                } else {
                    //订单号
                    UmbrellaHardwareManageLogExample logExample = new UmbrellaHardwareManageLogExample();
                    logExample.setOrderByClause("start_time desc");//倒序排序，确保获取到最新的
                    UmbrellaHardwareManageLogExample.Criteria logCriteria = logExample.createCriteria();
                    //未删除
                    logCriteria.andFlagEqualTo(1);
                    //状态初始化
                    logCriteria.andResultEqualTo(0);
                    logCriteria.andUseridEqualTo(account);
                    logCriteria.andMachineCodeEqualTo(machineCode);
                    logCriteria.andEndTimeIsNull();
                    logCriteria.andCommandEqualTo(ApiConstant.UMBRELLA_MACHINE_COMMAND_10112);
                    UmbrellaHardwareManageLog log = umbrellaHardwareManageLogService.selectFirstByExample(logExample);
                    if (log != null) {
                        //通知机器端关锁
                        /**
                         {
                             "command": 10113,
                             “machineCode”:”2018092700001",
                             “code”:1,//响应结果(1,成功；0，失败)
                             "message":"",
                             "dataInfo": {
                                 “orderNo":”20180929100020001",//交互订单
                                 “dataPackage”:{
                                     “account”: 10000004,
                                     “token”:”SDKJLJBB_JLKSDJFLKDSJFDSJFLJ-IJOIUEWRPOI”
                                 }
                             }
                         }
                         */
                        JSONObject machineDataInfo = new JSONObject();
                        machineDataInfo.put("orderNo", log.getOrderno());
                        machineDataInfo.put("dataPackage", recvData.getJSONObject("dataPackage"));
                        ApiResult machineNotifyInfo = new ApiResult(ApiResultConstant.SUCCESS.code, ApiResultConstant.SUCCESS.message, ApiConstant.UMBRELLA_MACHINE_COMMAND_10113, machineCode, machineDataInfo);
                        mq4UmbrellaMachineNotify.send(JsonUtil.object2Json(machineNotifyInfo), machineCode);

                        //组装返回数据
                        dataInfo.put("orderNo", log.getOrderno());
                        result.setCode(ApiResultConstant.SUCCESS.code);
                        result.setMessage(ApiResultConstant.SUCCESS.message);
                        result.setData(dataInfo);
                    } else {
                        result.setCode(ApiResultConstant.FAILED.code);
//                        result.setMessage(ApiResultConstant.FAILED.message);
                        result.setMessage("伞机出伞操作已结束。");
                        result.setData(dataInfo);
                    }

                }
            }
        }catch (Exception e){
            LOGGER.error("扫码结束出伞异常,异常信息:", e);
        }
        //使用mq消息将结束出伞处理失败通知客户端
        if(result.getCode() != ApiResultConstant.SUCCESS.code && account>0 && isMqMessage){
            mq4UmbrellaWechatappNotify.send(JsonUtil.object2Json(result), String.valueOf(account));
        }
        return result;
    }

}
